#include "T2CDialog.h"
#include <QApplication>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QTextEdit>
#include <QGridLayout>
#include <QFileDialog>
#include "common.h"


//-------------------------------------

T2CDialog::T2CDialog( QString h, int p, QWidget * parent ) :
    QFrame( parent ),
    iSZ_valid( false ),
    manager( new T2CManager() )
{
    resize( 640, 480 );

    lbl_host  = new QLabel( "SCADA ip:", this );
    lbl_port  = new QLabel( "Port:", this );
    lbl_cmd   = new QLabel( "Command:", this );
    lbl_i_SZ  = new QLabel( "i_SZ of object:", this );
    lbl_State = new QLabel( "State:", this );
    lbl_State->setAlignment( Qt::AlignCenter );

    lnedt_host = new QLineEdit( h, this );
    lnedt_port = new QLineEdit( QString::number( p ), this );
    lnedt_cmd  = new QLineEdit( /*"T2C VER"*/ /*"DAS 'IDF{88081}(<.OBJ.LNG, .OBJ.IDF>.CAT).CAT'"*/ /*"ARS GET ITV ARN=E4_5sec ANF=1372684120 IDF=[833691]"*/ "ARS GET ITV ARN=E4_5sec ANF=1372664150 END=1372662710 IDF=[833691]", this );
    inedt_i_SZ = new QLineEdit( "782522", this );

    btn_connect     = new QPushButton( "Connect to SCADA", this );
    btn_disconnect  = new QPushButton( "Disconnect SCADA", this );
    btn_exec        = new QPushButton( "Execute", this );
    btn_Subscribe   = new QPushButton( "Subscribe", this );
    btn_Unsubscribe = new QPushButton( "Unsubscribe", this );
    btnExecPackage  = new QPushButton( "Execute Package", this );

    txted_log = new QTextEdit;

    //Layout settings
    grdLayout = new QGridLayout;
    grdLayout->setSpacing( 5 );
    grdLayout->setMargin( 5 );
    grdLayout->addWidget( lbl_host,    0, 0 );
    grdLayout->addWidget( lnedt_host,  0, 1 );
    grdLayout->addWidget( lbl_port,    0, 2 );
    grdLayout->addWidget( lnedt_port,  0, 3 );
    grdLayout->addWidget( btn_connect, 0, 4 );
    grdLayout->addWidget( btn_disconnect, 0, 5 );

    grdLayout->addWidget( lbl_i_SZ,        1, 0 );
    grdLayout->addWidget( inedt_i_SZ,      1, 1, 1, 3 );
    grdLayout->addWidget( btn_Subscribe,   1, 4 );
    grdLayout->addWidget( btn_Unsubscribe, 1, 5 );

    grdLayout->addWidget( lbl_State, 2, 0, 1, 6 );

    grdLayout->addWidget( lbl_cmd,   3, 0 );
    grdLayout->addWidget( lnedt_cmd, 3, 1, 1, 3 );
    grdLayout->addWidget( btn_exec,  3, 4 );
    grdLayout->addWidget( btnExecPackage,  3, 5 );

    grdLayout->addWidget( txted_log, 4, 0, 1, 6 );

    setLayout( grdLayout );

    btn_connect->setEnabled( true );
    btn_disconnect->setEnabled( false );
    btn_exec->setEnabled( false );
    btn_Subscribe->setEnabled( false );
    btn_Unsubscribe->setEnabled( false );

    setWindowTitle( "T2C Manager Console" );

    connect( btn_connect, SIGNAL(clicked()), SLOT(slotConnect()) );
    connect( btn_disconnect, SIGNAL(clicked()), SLOT(slotDisconnect()) );
    connect( btn_exec, SIGNAL(clicked()), SLOT(slotExec()) );
    connect( btn_Subscribe, SIGNAL( clicked() ), this, SLOT( slotSubscribe() ) );
    connect( btn_Unsubscribe, SIGNAL( clicked() ), this, SLOT( slotUnsubscribe() ) );
    //connect( manager, SIGNAL( sgnValueRecieved(QString) ), this, SLOT( sltValueReceived(QString) ));
    connect( manager, SIGNAL( sgnSendToLog(QString) ), this, SLOT( sltReceiveLog(QString) ) );
    connect( manager, SIGNAL( sgnConnected() ), this, SLOT( sltT2CManChangedConnection() ) );
    connect( manager, SIGNAL( sgnDisconnected() ), this, SLOT( sltT2CManChangedConnection() ) );

    connect( btnExecPackage, SIGNAL( clicked() ), SLOT( slotExecPackage() ) );

    setEnabledControls( false );
    btn_connect->setEnabled( (bool)manager );
    setAttribute( Qt::WA_DeleteOnClose, true );
}

//-------------------------------------

T2CDialog::~T2CDialog()
{
    //slotUnsubscribe();
    //manager->~CT2CManager();
    //while( manager->isRunning ){}
    manager->Disconnect();
    delete manager;
}

//-------------------------------------

void T2CDialog::slotConnect()
{
    host = /*QHostAddress*/( lnedt_host->text() );
    port = lnedt_port->text().toInt();

    manager->Connect( host, port );
/*
    btn_connect->setEnabled( false );
    btn_disconnect->setEnabled( true );
    btn_exec->setEnabled( true );
    btn_Subscribe->setEnabled( true );
    btn_Unsubscribe->setEnabled( false );*/
}

//-------------------------------------

void T2CDialog::slotDisconnect()
{
    manager->Disconnect();
/*
    btn_connect->setEnabled( true );
    btn_disconnect->setEnabled( false );
    btn_exec->setEnabled( false );
    btn_Subscribe->setEnabled( false );
    btn_Unsubscribe->setEnabled( false );*/
}

//-------------------------------------

void T2CDialog::slotExec()
{
    if( manager )
    {
        //txted_log->clear();
        QTime t;
        t.start();
        txted_log->append( "===> '" + lnedt_cmd->text() + "' Started at: " + QTime::currentTime().toString( "hh:mm:ss.zzz" ) );
        manager->ExecCmd( lnedt_cmd->text() );
        //manager->getVariable( 782522 );
        //manager->waitForReady();
        //manager->probeVariable( 782522 );
        //manager->WaitngForResponse();
        //txted_log->append( manager->GetResponse() );
        //txted_log->append( "===> Stopped at:" + QTime::currentTime().toString( "hh:mm:ss.zzz" ) );
        //txted_log->append( QString( "===>   Time elapsed: %1 ms" ).arg( t.elapsed() ) );
    }

}

//-------------------------------------

void T2CDialog::slotSubscribe()
{
    check_iSZ();
    if( iSZ_valid )
    {
        manager->subscribe( iSZ );
        btn_Subscribe->setEnabled( false );
        btn_Unsubscribe->setEnabled( true );
    }
}

//-------------------------------------

void T2CDialog::slotUnsubscribe()
{
    check_iSZ();
    if( iSZ_valid )
    {
        manager->unsubscribe( iSZ );
        btn_Subscribe->setEnabled( true );
        btn_Unsubscribe->setEnabled( false );
    }
}

//-------------------------------------

void T2CDialog::check_iSZ()
{
    QString i_SZ = inedt_i_SZ->text();

    if( i_SZ.length()  )
    {
        QRegExp reg( "[0-9]+" );
        QRegExpValidator v( reg, 0 );
        int pos = 0;
        if( v.validate( i_SZ, pos ) == QValidator::Acceptable )
        {
            iSZ = i_SZ.toLongLong();
            iSZ_valid = true;
        }
        else
        {
            iSZ_valid = false;
        }
    }
}

//-------------------------------------

void T2CDialog::sltValueReceived( QString t )
{
    lbl_State->setText( "State:   " + t );
    lnedt_cmd->setText( t );
    txted_log->append( t );
}

//-------------------------------------

void T2CDialog::sltReceiveLog( QString txt )
{
    txted_log->append( txt );
}

//-------------------------------------

void T2CDialog::setEnabledControls( bool connected )
{
    btn_connect->setEnabled( !connected );
    btn_disconnect->setEnabled( connected );
    btn_exec->setEnabled( connected );
    txted_log->setEnabled( connected );
    inedt_i_SZ->setEnabled( connected );
    btn_Subscribe->setEnabled( connected );
    btn_Unsubscribe->setEnabled( connected );
    lnedt_cmd->setEnabled( connected );
    btnExecPackage->setEnabled( connected );
}

//-------------------------------------

void T2CDialog::sltT2CManChangedConnection()
{
    setEnabledControls( manager->isConnected() );
    if( manager->isConnected() )
        txted_log->append( "==>Connected" );
    else
        txted_log->append( "==>Disconnected" );
}

//-------------------------------------

void T2CDialog::slotExecPackage()
{
    QString fn = QFileDialog::getOpenFileName( this, "Open Chart Data File", "", "Double Pair Data File ( *.cssc )" );
    if( fn.isEmpty() )
        return;

    QFile file( fn );

    if( file.open( QFile::ReadOnly | QIODevice::Text ) )
    {
        QTextStream out( &file );
        QStringList sl = out.readAll().split( "\n" );
        file.close();

        QString cmd;

        for( int i=0; i < sl.count(); ++i )
        {
            cmd = sl.at( i );

            if( cmd.isEmpty() )
                continue;

            cmd = cmd.replace( "\"", "\\\"" );

            manager->ExecCmd( cmd );
            //manager->WaitngForResponse();
            //manager->UNLOCK();
            txted_log->append( "==>DONE: " + cmd );

        }
    }
}

//-------------------------------------















